require.config({
  baseUrl: "./script/",
  paths: {
    three: '../../lib/three',
    stats: '../../lib/stats.min',
    'three.OBJLoader': '../../lib/OBJLoader'
  }
})

const requestAnimationFrame = window.requestAnimationFrame
  || window.mozRequestAnimationFrame
  || window.webkitRequestAnimationFrame
  || window.msRequestAnimationFrame
window.requestAnimationFrame = requestAnimationFrame;

require(['stats', 'three', 'three.OBJLoader'], function (Stats, THREE) {
  let scene = null;
  let camera = null;
  let renderer = null;

  let mesh = null;
  let id = null;
  let stat = null

  init()
  function init() {
    stat = new Stats();
    stat.domElement.style.position = 'absolute';
    stat.domElement.style.left = '';
    stat.domElement.style.right = '0px';
    stat.domElement.style.top = '0px';
    document.body.appendChild(stat.domElement);

    // 渲染器
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(400, 300);
    document.body.appendChild(renderer.domElement);
    renderer.setClearColor(0x000000);
    scene = new THREE.Scene();

    camera = new THREE.OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
    camera.position.set(15, 25, 25);
    camera.lookAt(new THREE.Vector3(0, 2, 0));
    scene.add(camera);

    const loader = new THREE.OBJLoader()
    loader.load('../lib/port.obj', function(obj) {
      obj.traverse(function(child) {
        if (child instanceof THREE.Mesh) {
          child.material = new THREE.MeshLambertMaterial({
            color: 0xffff00,
            side: THREE.DoubleSide
          });
        }
      });

      mesh = obj;
      scene.add(obj);
    });

    const light = new THREE.DirectionalLight(0xffffff)
    light.position.set(20, 10, 5);
    scene.add(light);

    id = requestAnimationFrame(draw);
  }

  function draw() {
    stat.begin();
    if (mesh !== null) {
      mesh.rotation.y += 0.01;
      if (mesh.rotation.y > Math.PI * 2) {
        mesh.rotation.y -= Math.PI * 2;
      }
    }
    renderer.render(scene, camera);
    id = requestAnimationFrame(draw);
    stat.end();
  }

  function stop() {
    if (id !== null) {
      cancelAnimationFrame(id);
      id = null;
    }
  }

  function start() {
    if (id === null) {
      id = requestAnimationFrame(draw);
    }
  }

  Object.assign(window, {
    stop, start
  })

})
